﻿using Sobiens.Connector.Admin.UI;
using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Collections;
using System.Xml.Serialization;
using System.Data;
using System.Linq;
using System.Text;
using System.Collections.Generic;

namespace Sobiens.Connector.Admin.SP.WebParts.ConnectorAdmin
{

    [ToolboxItemAttribute(false)]
    public partial class ConnectorAdmin : WebPart, IConnectorAdminView
    {
        private ConnectorAdminPresenter _presenter;
        internal ConnectorAdminModel Model { get; set; }
        private String _configurationId = null;

        public String SelectedConfigurationId
        {
            get
            {
                return (DropDownListConfigurations.SelectedValue == Guid.Empty.ToString()) 
                    ? HiddenFieldSelectedConfigurationUniqueIdClient.Value 
                    : DropDownListConfigurations.SelectedValue;
            }
        }

        // [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Assert, UnmanagedCode = true)]
        public ConnectorAdmin()
        {

        }

        #region page life cycle

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeControl();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            _presenter = new ConnectorAdminPresenter(this);

            if (String.IsNullOrEmpty(Page.Request.QueryString.Get("ConfigId")))
            {
                if (!Page.IsPostBack)
                {
                    _presenter.Init();
                }
            }
            else
            {
                _configurationId = Page.Request.QueryString["ConfigId"].ToString();
            }
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {

            if(_configurationId == null)
            {
                writer.Write(GenerateJsAndCss());
                if (Model != null)
                {
                    writer.Write(GenerateJSObject(Model.SelectedConfiguration.JSONData, Model.AllConfigurationsJSON));
                }
                base.Render(writer);
            }
            else
            {
                String xml = _presenter.GetConfigUrlXml(_configurationId);
                writer.Write(xml);
            }
        }

        #endregion

        #region event handlers


        protected void DropDownListConfigurations_SelectedIndexChanged(object sender, EventArgs e)
        {
            _presenter.LoadCurrentConfiguration();
        }

        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            _presenter.SaveCurrentConfigurationData(SelectedConfigurationId, HiddenFieldJSONCurrentConfigurationData.Value);
        }

        #endregion

        public void PopulateFromModel(ConnectorAdminModel model)
        {
            Model = model;
            DropDownListConfigurations.DataSource = model.AllConfigurations;
            DropDownListConfigurations.DataTextField = "Value";
            DropDownListConfigurations.DataValueField = "Key";
            DropDownListConfigurations.DataBind();
            DropDownListConfigurations.SelectedValue = model.SelectedConfiguration.UniqueId.ToString();
            
        }

        private String GenerateJSObject(String appConfigJSON, String allConfigurationsJSON)
        {

            if(String.IsNullOrEmpty(appConfigJSON))
            {
                appConfigJSON = @"{""DetailedLogMode"" : false,\
                                 ""SiteSettings"" : []}";
            }

            if (String.IsNullOrEmpty(allConfigurationsJSON))
            {
                allConfigurationsJSON = @"{""Configurations"" : []}";
            }

            String js = string.Format(@"<script type=""text/javascript"">
                                            var SCA = SCA || {{}};
                                            SCA.AppConfiguration = jQuery.parseJSON('{0}');
                                            SCA.AllConfigurations = jQuery.parseJSON('{1}');
                                        </script>", appConfigJSON, allConfigurationsJSON);
            return js;
        }
        
        private String GenerateJsAndCss()
        {
            String url = SPContext.Current.Web.Url;
            const string JS = @"<script src=""{0}/Style%20Library/Sobiens.Connector.Admin/JS/{1}"" type=""text/javascript""></script>";
            const string CSS = @"<link rel=""stylesheet"" type=""text/css"" href=""{0}/Style%20Library/Sobiens.Connector.Admin/CSS/{1}"" />";

            List<String> jsFiles = new List<String>{"Libs/jquery-1.8.3.js","Libs/jquery-ui-1.9.1.custom.min.js","Libs/validity.js","Libs/jquery.cookie.js","Libs/jquery.dynatree.min.js",
                "UI/SCA.UI.SiteSettings.Dialog.js","UI/SCA.UI.SiteSettings.Table.js",
                "UI/SCA.UI.DocumentTemplates.Dialog.js","UI/SCA.UI.DocumentTemplates.Table.js",
                "UI/SCA.UI.DocumentTemplateMappings.Table.js","UI/SCA.UI.DocumentTemplateMappings.Dialog.js",
                "UI/SCA.UI.ExplorerLocations.Table.js","UI/SCA.UI.ExplorerLocations.Dialog.js",
                "UI/SCA.UI.OutlookConfigurations.js",
                "UI/SCA.UI.Mappings.Table.js", "UI/SCA.UI.Mappings.Dialog.js",
                "UI/SCA.UI.Configuration.Dialog.js",
                "DAL/SCA.DAL.SP.js",
                "UI/SCA.UI.LocationSelection.Dialog.js",
                "UI/SCA.UI.Main.js", "UI/SCA.SPDialog.js"};

            List<String> cssFiles = new List<String>{"jquery-ui-1.9.1.custom.min.css","jquery.validity.css","dynatree/ui.dynatree.css"};
                                   
            StringBuilder sb = new StringBuilder();
            jsFiles.ForEach(jsFile => sb.AppendFormat(JS, url, jsFile));
            cssFiles.ForEach(cssFile => sb.AppendFormat(CSS, url, cssFile));
            
            return sb.ToString();
        }
    }
}
